<!-- 员工离职申请 -->
<template>
  <view>
    <u-form
      :model="model"
      :rules="rules"
      ref="form"
      labelPosition="top"
      labelWidth="auto"
      :labelStyle="{
      	fontSize: '14px',
      	color: '#B2B2B2',
      	lineHight: '20px'
      }"
    >
      <view class="basic-style">
        <view class="basic-title basic-border">基本信息</view>
				<u-form-item label="单据编号" prop="billNo" required>
				  <u--input disabled placeholder="请输入单据编号" v-model="model.billNo"></u--input>
				</u-form-item>
        <u-form-item label="离职人员" prop="employeeId">
          <h-select-person-input
            style="width: 100%"
            disabled
            v-model="model.employeeId"
            placeholder=""
            border="surround"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
            objectField="model.employeeId"
          ></h-select-person-input>
        </u-form-item>
        <u-form-item label="人员编号" prop="employeeNo">
          <u--input disabled placeholder="请输入人员编号" v-model="model.employeeNo"></u--input>
        </u-form-item>
        <u-form-item label="所在部门" prop="departmentId">
          <h-select-depart-input
            disabled
            v-model="model.departmentId"
            :departName="model.proposerDeptText"
            placeholder="请选择部门"
            border="surround"
            style="width: 100%"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
            :title.sync="model.proposerDeptText"
          ></h-select-depart-input>
        </u-form-item>
        <u-form-item label="所属团队" prop="teamId" required>
          <h-select-team-input
            disabled
            style="width: 100%"
            v-model="model.teamId"
            objectField="model.teamId"
            placeholder="请选择所属团队"
            border="surround"
						suffixIcon="arrow-down-fill"
						:suffixIconStyle="{ color: '#B2B2B2' }"
            :tdlx="3"
          />
        </u-form-item>
				<u-form-item label="所属公司" prop="workUnit" required>
				  <h-select-company-input
				    style="width: 100%"
				    v-model="model.workUnit"
				    objectField="model.workUnit"
				    placeholder="请选择所属公司"
				    border="surround"
						suffixIcon="arrow-down-fill"
						:suffixIconStyle="{ color: '#B2B2B2' }"
				  />
				</u-form-item>
        <u-form-item label="岗位名称" prop="positionId">
          <h-select-input-tag
            disabled
            class="w-100"
            v-model="model.positionId"
            objectField="model.positionId"
            placeholder="请选择岗位名称"
            border="surround"
						suffixIcon="arrow-down-fill"
						:suffixIconStyle="{ color: '#B2B2B2' }"
            dictName="sys_position,name,id,del_flag = 0 and audit_status=2"
          ></h-select-input-tag>
        </u-form-item>
        <u-form-item label="入职日期" prop="entryTime">
          <h-time-select
            disabled
            mode="date"
            v-model="model.entryTime"
            placeholder="请选择入职日期"
            border="surround"
            suffixIcon="calendar-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
          ></h-time-select>
        </u-form-item>
        <u-form-item label="合同到期日期" prop="contractTime">
          <h-time-select
            disabled
            mode="datetime"
            v-model="model.contractTime"
            placeholder="请选择合同到期日期"
            border="surround"
            suffixIcon="calendar-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
          ></h-time-select>
        </u-form-item>
        <u-form-item label="员工类别" prop="employeeType">
          <h-select-input-tag
            class="w-100"
						disabled
            v-model="model.employeeType"
            objectField="model.employeeType"
            placeholder="请选择员工类别"
            border="surround"
						suffixIcon="arrow-down-fill"
						:suffixIconStyle="{ color: '#B2B2B2' }"
            dictName="employee_type"
          ></h-select-input-tag>
        </u-form-item>
        <u-form-item label="离职类型" prop="resignType" required>
          <h-select-input-tag
            class="w-100"
            v-model="model.resignType"
            objectField="model.resignType"
            placeholder="请选择离职类型"
            border="surround"
						suffixIcon="arrow-down-fill"
						:suffixIconStyle="{ color: '#B2B2B2' }"
            dictName="resign_type"
          ></h-select-input-tag>
        </u-form-item>
        <u-form-item label="离职原因" prop="resignReason" required>
          <u--textarea :confirm-type="null" maxlength="500" count v-model="model.resignReason" placeholder="请输入离职原因"></u--textarea>
        </u-form-item>
        <u-form-item label="备注" prop="remark">
          <u--textarea :confirm-type="null" count  maxlength="500" v-model="model.remark" placeholder="请输入备注"></u--textarea>
        </u-form-item>
      </view>

      <view class="basic-style">
        <view class="basic-title basic-border">评价信息</view>
        <u-form-item label="离职日期" prop="resignTime" required>
          <h-time-select
            mode="date"
            v-model="model.resignTime"
            placeholder="请选择离职日期"
            border="surround"
            suffixIcon="calendar-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
						@change="resignTimeChange"
          ></h-time-select>
        </u-form-item>
        <u-form-item label="薪资截止日期" prop="salaryEndDate" required>
          <h-time-select
            mode="date"
            v-model="model.salaryEndDate"
            placeholder="请选择薪资截止日期"
            border="surround"
            suffixIcon="calendar-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
          ></h-time-select>
        </u-form-item>
        <u-form-item label="社保截止日期" prop="socialSecurityDeadline" required>
          <h-time-select
            mode="date"
            v-model="model.socialSecurityDeadline"
            placeholder="请选择社保截止日期"
            border="surround"
            suffixIcon="calendar-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
          ></h-time-select>
        </u-form-item>
        <u-form-item label="公积金截止日期" prop="accumulationFundDate" required>
          <h-time-select
            mode="date"
            v-model="model.accumulationFundDate"
            placeholder="请选择公积金截止日期"
            border="surround"
            suffixIcon="calendar-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
          ></h-time-select>
        </u-form-item>
        <u-form-item label="资产/物品" prop="assets" required>
          <u--input placeholder="请输入资产/物品" v-model="model.assets"></u--input>
        </u-form-item>
        <u-form-item label="借款/次数" prop="loanMoney" required>
          <u--input placeholder="请输入借款/次数" v-model="model.loanMoney"></u--input>
        </u-form-item>
        <u-form-item label="工作交接" prop="workHandover" required>
          <h-select-person-input
            v-model="model.workHandover"
            style="width: 100%"
            placeholder="请选择工作交接"
            searchPlaceholder="请输入"
            border="surround"
						objectField="model.workHandover"
            suffixIcon="arrow-down-fill"
            :suffixIconStyle="{ color: '#B2B2B2' }"
          ></h-select-person-input>
        </u-form-item>
        <u-form-item label="档案资料" prop="profiles" required>
          <u--input placeholder="请输入档案资料" v-model="model.profiles"></u--input>
        </u-form-item>
        <!-- <u-form-item label="培训扣款(元)" prop="trainingDeduction" required>
					<h-money-input placeholder="请输入培训扣款" v-model="model.trainingDeduction"></h-money-input>
        </u-form-item> -->
        <u-form-item label="电脑扣款(元)" prop="computerDeduction" required>
					<h-money-input placeholder="请输入电脑扣款" v-model="model.computerDeduction"></h-money-input>
          <!-- <u--input type="number" v-number-normal placeholder="请输入电脑扣款" v-model="model.computerDeduction"></u--input> -->
        </u-form-item>
        <u-form-item label="其他扣款(元)" prop="otherDeduction">
					<h-money-input placeholder="请输入其他扣款" v-model="model.otherDeduction"></h-money-input>
          <!-- <u--input type="number" v-number-normal placeholder="请输入其他扣款" v-model="model.otherDeduction"></u--input> -->
        </u-form-item>
      </view>
			
			<view class="basic-style">
			  <view class="basic-title basic-border pt-1">培训扣款(元)</view>
			  <u-collapse>
			    <u-collapse-item :title="`培训扣款明细表单${index + 1}`" v-for="(item, index) in formData" :key="index">
			      <TrainingCutPaymentInfo
			        :item="item"
			        :index="index"
			        @edit="handleEditForm"
			        @remove="handleRemoveForm"
			        @copy="handleCopyForm"
			      />
			    </u-collapse-item>
			  </u-collapse>
			</view>

      <view class="basic-style">
        <view class="basic-title basic-border">附件信息</view>
        <view class="py-1 space-y-1" style="width: 100%">
          <view style="color: red">提示：请等待附件上传完成，再点击保存，否则附件无法保存成功！</view>
          <h-upload-file v-model="model.attachment" :isIcon="false"></h-upload-file>
          <file-list v-if="model.attachment" v-model="model.attachment" :isDelete="true"></file-list>
        </view>
      </view>

      <!-- <view class="space-x-1 mt-1 px-1 pb-1" style="display: flex">
        <u-button type="primary" text="保存提交" :loading="loading" @click="onSubmit"></u-button>
        <u-button type="primary" text="保存草稿" :loading="loading" @click="onDraft"></u-button>
      </view> -->
			
			<view class="space-x-1 px-1 btn_position">
				<u-button :disabled="isSubmit" type="primary" :plain="true" text="保存到草稿" @click="onDraft"></u-button>
				<u-button :disabled="isSubmit"  type="primary"  text="保存并提交" @click="onSubmit"></u-button>
			</view>
			<view style="height: 100rpx;"></view>
    </u-form>
		
		<u-toast ref="uToast"></u-toast>
		<ProcessNodeConfiguration ref="processConfig" @ok="onOk"></ProcessNodeConfiguration>
		
  </view>
</template>

<script>
import { mapState } from 'vuex'
import moment from 'moment'
import { add, info,edit, queryPostRecordByInfo, queryContractByEmployeeId, erpEmployeeTrainingList } from '@/api/hr/EmploeeLeaveApply'
import ProcessNodeConfiguration from '@/components/ProcessNodeConfiguration/ProcessNodeConfiguration.vue' // 流程节点配置人员选择弹窗
import fileList from '@/pages/synergy/components/fileList.vue'
import TrainingCutPaymentInfo from './components/TrainingCutPaymentInfo.vue'
import http from '@/utils/request/index'
export default {
  name: 'EmploeeLeaveApply',
  components: {
    fileList,
		ProcessNodeConfiguration,
		TrainingCutPaymentInfo
  },
  data() {
    const validatorFlag = async (rule, value, callback) => {
      if (value) {
        if (!this.flag) {
          callback('请保存试用期考核表！')
          return
        }
        callback()
      }
      callback()
    }
    return {
			isSubmit: false, // 控制按钮是否可以点击
      backUpProvisionBroad: '',
      showBusinessSegment: false,
      exportTeamId: '',
      flag: false,
      index: null,
      showFormModal: false,
      confirmModal: false,
      loading: false,
      id: '',
      exportWarehouseList: [],
      foldWarehouseList: [],
      dataSource2: [],
      basicForm: {},
      formData: [],
      model: {
				billNo: '',
        employeeId: null,
        employeeNo: null,
        departmentId: null,
        teamId: null,
				workUnit: null,
        positionId: null,
        entryTime: null,
        contractTime: null,
        employeeType: null,
        resignType: null,
        resignReason: '',
        remark: '',
        resignTime: null,
        salaryEndDate: null,
        socialSecurityDeadline: null,
        accumulationFundDate: null,
        assets: null,
        loanMoney: null,
        workHandover: null,
        profiles: null,
        trainingDeduction: null,
        computerDeduction: null,
        otherDeduction: null,
        attachment: null,
      },
      rules: {
				billNo: [{ required: true, message: '请输入单据编号!', trigger: ['blur', 'change'] }],
        teamId: [{ required: true, message: '请选择所属团队!', trigger: ['blur', 'change'] }],
        workUnit: [{ required: true, message: '请选择所属公司!', trigger: ['blur', 'change'] }],
        bpmBizTitle: [{ required: true, message: '请输入流程标题!', trigger: ['blur', 'change'] }],
        resignType: [{ required: true, message: '请选择离职类型!', trigger: ['blur', 'change'] }],
        resignReason: [{ required: true, message: '请输入离职原因!', trigger: ['blur', 'change'] }],
        resignTime: [{ required: true, message: '请选择离职日期!', trigger: ['blur', 'change'] }],
        salaryEndDate: [{ required: true, message: '请选择薪资截止日期!', trigger: ['blur', 'change'] }],
        socialSecurityDeadline: [{ required: true, message: '请选择社保截止日期!', trigger: ['blur', 'change'] }],
        accumulationFundDate: [{ required: true, message: '请选择社公积金截止日期!', trigger: ['blur', 'change'] }],
        assets: [{ required: true, message: '请输入资产/物品!', trigger: ['blur', 'change'] }],
        loanMoney: [{ required: true, message: '请输入借款/次数!', trigger: ['blur', 'change'] }],
        workHandover: [{ required: true, message: '请选择工作交接人!', trigger: ['blur', 'change'] }],
        profiles: [{ required: true, message: '请输入档案资料!', trigger: ['blur', 'change'] }],
        // trainingDeduction: [
        //   { required: true, pattern: /^(([1-9][0-9]*|0)|([0]\.\d{0,2}|[1-9][0-9]*\.\d{0,2}))$/, message: '请输入正确的培训扣款!', trigger: ['blur', 'change'] },
        // ],
        computerDeduction: [
          { required: true, pattern: /^(([1-9][0-9]*|0)|([0]\.\d{0,2}|[1-9][0-9]*\.\d{0,2}))$/, message: '请输入正确的电脑扣款!', trigger: ['blur', 'change'] },
        ],
        otherDeduction: [
          { required: false, pattern: /^(([1-9][0-9]*|0)|([0]\.\d{0,2}|[1-9][0-9]*\.\d{0,2}))$/, message: '请输入正确的其他扣款!' ,trigger: ['blur', 'change'] },
        ],
      },
			 //代码生成后需手动设置流程编码
			flowCode: 'onl_erp_hr_employee_resign_bill',
			formUrl: "erp/hr/resign/modules/ErpHrEmployeeResignBillForm",
			formUrlMobile: "/pages/synergy/erpHrEmployeeResignBillForm",
			processId:"1540236705217404929",
			beanName:"erpHrEmployeeResignBillServiceImpl"
    }
  },
  onLoad({ id }) {
    this.id = id || ''
  },
  created() {
    if (this.id) {
      this.initInfo()
    } else {
      this.initForm()
			this.generatedFormNumber()
    }
  },
  computed: {
    ...mapState(['userInfo']),
  },
  methods: {
		// 获取编号
		generatedFormNumber() {
			http.get('/api/erp/base/generatedFormNumber', { prefix: 'LZSQ', subSystemCode: '02' }).then(res => {
				if (res.success) {
					this.$set(this.model, 'billNo', res.result)
				}
			})
		},
    /**
     * 弹窗点击确认
     */
    handleConfirmModalConfirm() {
      this.formData = []
      this.confirmModal = false
    },
    /**
     * 弹窗点击取消
     */
    handleConfirmModalCancel() {
      // 还原修改的数据
      if (this.resetKey) {
        let realKey = this.resetKey.replace('backUp', '')
        realKey = realKey[0].toLowerCase() + realKey.slice(1)
        this.isReset = true
        this.$set(this.model, realKey, this[this.resetKey])
        setTimeout(() => (this.isReset = false), 0)
      }
      this.confirmModal = false
    },
    /**
     * 修改值时，检查是否需要弹出对话框确认修改
     * 取消 modal 的时候，需要将值还原
     * @param {String} key BasicForm 中的key值
     * @param {Function} fn 回调函数
     * @param {any} data 回调函数参数
     */
    checkSwitch(key, fn, data) {
      this.$nextTick(() => {
        if (this.isReset) return
        const firstChar = key[0].toUpperCase()
        key = firstChar + key.slice(1)
        const oldData = this[`backUp${key}`]
        if (oldData && oldData !== this.model[key]) {
          this.confirmModal = true
          this.resetKey = `backUp${key}`
        } else {
          fn && fn(data)
        }
      })
    },
    handleCopyForm([item, index]) {
      this.formData.push({
        ...item,
      })
      this.$u.toast('复制成功')
    },
    handleEditForm([item, index]) {
      this.basicForm = { ...item }
      this.index = index
      this.showFormModal = true
    },
    handleRemoveForm(item) {
      this.formData = this.formData.filter((i) => i !== item)
    },
    closeFormModal() {
      this.$refs.dataForm.reset()
      this.basicForm = {}
      this.index = null
    },
    openFormModal() {
      this.$refs.dataForm.basicForm = this.basicForm
    },
    addForm() {
      this.index = null
      this.showFormModal = true
    },
    /**
     * 子表单新增点击确认
     */
    handleFormSubmit([data, index]) {
      this.showFormModal = false
      if (typeof index === 'number') {
        this.$set(this.formData, index, data)
      } else {
        this.formData.push(data)
      }
    },
    // 初始化新增需要的数据
    initForm() {
      const userInfo = this.userInfo
      this.$set(this.model, 'employeeId', userInfo.empId)
      this.$set(this.model, 'employeeNo', userInfo.employee.employeeNo)
      this.$set(this.model, 'departmentId', userInfo.deptId)
      
			const date = moment(userInfo.employee.joinDate);
			const formattedDate = date.format("YYYY-MM-DD");
			this.$set(this.model, 'entryTime', formattedDate)
      this.$set(this.model, 'employeeType', userInfo.employee.employeeType)
      this.$set(this.model, 'bpmBizTitle', userInfo.employee.name)
			this.getPersonList()
      queryContractByEmployeeId({ employeeId: userInfo.empId }).then((res) => {
        if (res.success) {
          let data = res.result
          if (data) {
            if (data[0]) {
              this.$set(this.model, 'contractTime', data[0].endDate)
            } else {
              this.$u.toast('您暂无员工合同！')
            }
            // this.edit(this.model)
          }
        }
      })
      queryPostRecordByInfo({ employeeId: userInfo.empId, departId: userInfo.deptId }).then((res) => {
        if (res.success) {
          let data = res.result
          if (data) {
            this.$set(this.model, 'teamId', data[0].teamId)
            this.$set(this.model, 'positionId', data[0].postId)
            // this.edit(this.model)
          }
        }
      })
    },
    edit(record) {
      this.$refs.form.resetFields()
      this.model = Object.assign({}, record)
    },
    async initInfo() {
			const empId = uni.getStorageSync('userInfo').empId
      const response = await info({ employeeId: empId })
      const data = response.success?response.result.records[0] : {}
			this.model = Object.assign({}, data)
			this.getPersonList()
			this.$refs.form.resetFields()
    },
		// 获取子表信息
		getPersonList() {
			var params = {
				employeeId: this.model.employeeId,
				pageNo: 1,
				pageSize: -1
			}
			erpEmployeeTrainingList(params).then(res => {
				if (res.success) {
					this.formData = res.result.records || res.result
					this.calculateRemainingAmount() // 计算扣款金额
				} else {
					this.formData = []
				}
			}).catch(err => {
				uni.showToast({
					title: err.message,
					icon: 'none'
				})
			})
		},
		// 选择离职日期
		resignTimeChange () {
			this.calculateRemainingAmount()
		},
		// 计算剩余应扣款
		calculateRemainingAmount() {
			if (this.formData && this.formData.length > 0) {
				this.formData.map(item => {
					if (this.model.resignTime && item.serviceEndDate) {
						// 判断离职日期是否大于结束日期
						if (moment(this.model.resignTime).isAfter(item.serviceEndDate)) {
							item.remainingDeductions = '0.00'
							return item
						} else {
							// 离职日期小于开始日期
							if (moment(item.serviceStartDate).isAfter(this.model.resignTime)) {
								item.remainingDeductions = '0.00'
								return item
							}
							const diffInDays = moment(item.serviceEndDate).diff(moment(this.model.resignTime), 'days');
							item.remainingDeductions = ((diffInDays / Number(item.trainingServiceLimit || 0)) * (item.trainingFee || 0)).toFixed(2)
							return item
						}
					} else {
						item.remainingDeductions = '0.00'
						return item
					}
				})
			}
		},
    validateForm() {
      return this.$refs.form.validate()
    },
    async onSubmit() {
      await this.validateForm()
			this.isSubmit = true
			await this.$set(this.model, 'employeeTrainingList', this.formData)
			// 计算培训扣款
			if (this.formData && this.formData.length > 0) {
				let total = 0
				this.formData.forEach((item, index) => {
					total += Number(item.remainingDeductions) || 0
				})
				this.$set(this.model, 'trainingDeduction', total.toFixed(2))
			} else {
				this.$set(this.model, 'trainingDeduction', 0)
			}
      try {
        this.loading = true
				var url = ''
				if (this.id) {
					url = edit
				} else {
					url = add
				}
        //fix:BUG#5030 离职申请单-退回流程，再次提交后，数据携带问题 start
        if (!this.model.otherDeduction) {
          this.$set(this.model, 'otherDeduction', 0)
        }
        //fix:BUG#5030 离职申请单-退回流程，再次提交后，数据携带问题 end

        const response = await url({
          ...this.model,
        })
        this.$u.toast(response.message)
        if (response.success) {
        	var that = this
        	// 获取流程列表
        	if (this.model.id) {
        		this.getProcessList(this.model.id)
        	} else {
        	// 判断添加的时候是否有返回id值
        		if (response.result) {
        			this.getProcessList(response.result)
        		}
        
        	}
        	this.$refs.uToast.show({
        		message: response.message,
        		type: 'default',
        		complete () {
        			// that.isSubmit = false
        		}
        	})
        }
      } finally {
        this.loading = false
      }
    },
    async onDraft() {
			this.isSubmit = true
			await this.$set(this.model, 'employeeTrainingList', this.formData)
			// 计算培训扣款
			if (this.formData && this.formData.length > 0) {
				let total = 0
				this.formData.forEach((item, index) => {
					total += Number(item.remainingDeductions) || 0
				})
				this.$set(this.model, 'trainingDeduction', total.toFixed(2))
			} else {
				this.$set(this.model, 'trainingDeduction', 0)
			}
			try {
				this.loading = true
					var url = ''
					if (this.id) {
						url = edit
					} else {
						url = add
					}
				const response = await url({
					...this.model
				})
				if (response.success) {
					this.$refs.uToast.show({
						message: response.message,
						type: 'default',
						complete () {
							this.isSubmit = false
							if (getCurrentPages().length > 1) {
								uni.navigateBack()
							} else {
								uni.reLaunch({
									url: '/pages/home/home'
								})
							}
							
						}
					})
				}
			} finally {
				this.loading = false
			}
    },
		
		// 获取流程列表
		getProcessList (id) {
			if (this.isSubmit) {
				this.$refs.processConfig.showPopup = true
				this.$refs.processConfig.formUrl = this.formUrl
				this.$refs.processConfig.formUrlMobile = this.formUrlMobile
				this.$refs.processConfig.flowCode = this.flowCode
				this.$refs.processConfig.edit(id, this.processId, this.beanName)
			}
		},
		// 提交流程成功
		onOk () {
			this.$refs.uToast.show({
				message: '提交成功',
				type: 'success',
				complete () {
					if (getCurrentPages().length > 1) {
						uni.navigateBack()
					} else {
						uni.reLaunch({
							url: '/pages/home/home'
						})
					}
					
				}
			})
		}
  },
  watch: {
    tenderFormData: {
      immediate: true,
      handler(val) {
        if (val?.length) {
          const total = val.reduce((total, item) => {
            return total + item.amount * item.budgetAmount
          }, 0)
          this.$set(this.model, 'projectBudget', String(total))
        } else {
          this.$set(this.model, 'projectBudget', String(0))
        }
      },
    },
    'model.provisionBroad'(current, old) {
      if (old && current && old !== current) {
        this.backUpProvisionBroad = old
      }
    },
  },
}
</script>

<style scoped lang="scss">
@import url('@/assets/inputStyle.scss');
.trip-form-data {
  ::v-deep {
    .u-form-item__body {
      padding-top: 2px;
      padding-bottom: 2px;
    }
  }
}
.checkbox-item {
  display: flex;
  align-items: center;
}
</style>
